package cn.itcast.lucene;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

public class QueryLucene {
    @Test
    public void testQuery() throws IOException, ParseException {
        // 初始化索引库对象
        Directory directory = FSDirectory.open(new File("D:\\tmp\\indexDir"));

        // 索引读取工具
        IndexReader indexReader = DirectoryReader.open(directory);

        // 索引搜索对象
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        // 创建查询解析器对象
        QueryParser parser = new QueryParser("title", new IKAnalyzer());

        // 创建查询对象
        Query query = parser.parse("谷歌");

        // 执行搜索操作，返回值topDocs包含命中数，得分文档
        TopDocs topDocs = indexSearcher.search(query, Integer.MAX_VALUE);

        // 打印命中数
        System.out.println("一共命中："+topDocs.totalHits+"条数据");

        // 获得得分文档数组对象，得分文档对象包含得分和文档编号
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            System.out.println("得分："+scoreDoc.score);
            // 文档的编号
            int doc = scoreDoc.doc;
            System.out.println("编号："+doc);
            // 获取文档对象，通过索引读取工具
            Document document = indexReader.document(doc);
            System.out.println("id:"+document.get("id"));
            System.out.println("title:"+document.get("title"));
        }


    }

}
